package com.kurt.controller;

import com.kurt.annotation.Log;
import com.kurt.common.PageResult;
import com.kurt.common.Result;
import com.kurt.dto.VehicleDTO;
import com.kurt.dto.create.VehicleCreateRequest;
import com.kurt.dto.query.VehicleQueryRequest;
import com.kurt.dto.update.VehicleUpdateRequest;
import com.kurt.service.VehicleService;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.List;

/**
 * 车辆管理控制器
 * 提供车辆相关的REST API接口
 */
@Slf4j
@RestController
@RequestMapping("/vehicles")
@RequiredArgsConstructor
public class VehicleController extends BaseController {

    private final VehicleService vehicleService;

    /**
     * 创建车辆
     *
     * @param createRequest 创建请求
     * @return 创建结果
     */
    @Log(title = "创建车辆", businessType = 1)
    @PostMapping
    public Result<VehicleDTO> createVehicle(@Valid @RequestBody VehicleCreateRequest createRequest) {
        try {
            createRequest.setLoginUserId(getCurrentUserId());
            log.info("创建车辆请求: {}", createRequest.getLicensePlate());
            VehicleDTO vehicle = vehicleService.createVehicle(createRequest);
            return Result.success("车辆创建成功", vehicle);
        } catch (Exception e) {
            log.error("创建车辆失败", e);
            return Result.error("创建车辆失败: " + e.getMessage());
        }
    }

    /**
     * 更新车辆
     *
     * @param updateRequest 更新请求
     * @return 更新结果
     */
    @Log(title = "更新车辆", businessType = 2)
    @PutMapping
    public Result<VehicleDTO> updateVehicle(@Valid @RequestBody VehicleUpdateRequest updateRequest) {
        updateRequest.setLoginUserId(getCurrentUserId());
        try {
            log.info("更新车辆请求: {}", updateRequest.getId());
            VehicleDTO vehicle = vehicleService.updateVehicle(updateRequest);
            return Result.success("车辆更新成功", vehicle);
        } catch (Exception e) {
            log.error("更新车辆失败", e);
            return Result.error("更新车辆失败: " + e.getMessage());
        }
    }

    /**
     * 根据ID获取车辆详情
     *
     * @param id 车辆ID
     * @return 车辆详情
     */
    @GetMapping("/{id}")
    public Result<VehicleDTO> getVehicleById(@PathVariable("id") Long id) {
        try {
            log.info("获取车辆详情请求: {}", id);
            VehicleDTO vehicle = vehicleService.getVehicleById(id);
            return Result.success("获取车辆详情成功", vehicle);
        } catch (Exception e) {
            log.error("获取车辆详情失败", e);
            return Result.error("获取车辆详情失败: " + e.getMessage());
        }
    }

    /**
     * 分页查询车辆
     *
     * @param queryRequest 查询请求
     * @return 分页结果
     */
    @PostMapping("/page")
    public Result<PageResult<VehicleDTO>> getVehiclePage(@RequestBody VehicleQueryRequest queryRequest) {
        queryRequest.setLoginUserId(getCurrentUserId());
        try {
            log.info("分页查询车辆请求: {}", queryRequest);
            Page<VehicleDTO> page = vehicleService.getVehiclePage(queryRequest);
            PageResult<VehicleDTO> pageResult = PageResult.of(
                    page.getNumber() + 1,
                    page.getSize(),
                    page.getTotalElements(),
                    page.getContent()
            );
            return Result.success("分页查询车辆成功", pageResult);
        } catch (Exception e) {
            log.error("分页查询车辆失败", e);
            return Result.error("分页查询车辆失败: " + e.getMessage());
        }
    }

    /**
     * 查询车辆列表
     *
     * @param queryRequest 查询请求
     * @return 车辆列表
     */
    @PostMapping("/list")
    public Result<List<VehicleDTO>> getVehicleList(@RequestBody VehicleQueryRequest queryRequest) {
        queryRequest.setLoginUserId(getCurrentUserId());
        try {
            log.info("查询车辆列表请求: {}", queryRequest);
            List<VehicleDTO> vehicles = vehicleService.getVehicleList(queryRequest);
            return Result.success("查询车辆列表成功", vehicles);
        } catch (Exception e) {
            log.error("查询车辆列表失败", e);
            return Result.error("查询车辆列表失败: " + e.getMessage());
        }
    }

    /**
     * 删除车辆
     *
     * @param id 车辆ID
     * @return 删除结果
     */
    @Log(title = "删除车辆", businessType = 3)
    @DeleteMapping("/{id}")
    public Result<Boolean> deleteVehicle(@PathVariable("id") Long id) {
        try {
            log.info("删除车辆请求: {}", id);
            boolean success = vehicleService.deleteVehicle(id);
            return Result.success("车辆删除成功", success);
        } catch (Exception e) {
            log.error("删除车辆失败", e);
            return Result.error("删除车辆失败: " + e.getMessage());
        }
    }

    /**
     * 批量删除车辆
     *
     * @param ids 车辆ID列表
     * @return 删除结果
     */
    @Log(title = "批量删除车辆", businessType = 3)
    @DeleteMapping("/batch")
    public Result<Boolean> deleteVehicles(@RequestBody List<Long> ids) {
        try {
            log.info("批量删除车辆请求: {}", ids);
            boolean success = vehicleService.deleteVehicles(ids);
            return Result.success("批量删除车辆成功", success);
        } catch (Exception e) {
            log.error("批量删除车辆失败", e);
            return Result.error("批量删除车辆失败: " + e.getMessage());
        }
    }

    /**
     * 根据组织ID获取车辆列表
     *
     * @param organizationId 组织ID
     * @return 车辆列表
     */
    @GetMapping("/organization/{organizationId}")
    public Result<List<VehicleDTO>> getVehiclesByOrganizationId(@PathVariable("organizationId") Long organizationId) {
        try {
            log.info("根据组织ID获取车辆列表请求: {}", organizationId);
            List<VehicleDTO> vehicles = vehicleService.getVehiclesByOrganizationId(organizationId, getCurrentUserId());
            return Result.success("获取车辆列表成功", vehicles);
        } catch (Exception e) {
            log.error("获取车辆列表失败", e);
            return Result.error("获取车辆列表失败: " + e.getMessage());
        }
    }

    /**
     * 检查车牌号是否存在
     *
     * @param plateNumber 车牌号
     * @return 是否存在
     */
    @GetMapping("/exists/plate-number/{plateNumber}")
    public Result<Boolean> existsByPlateNumber(@PathVariable("plateNumber") String plateNumber) {
        try {
            log.info("检查车牌号是否存在请求: {}", plateNumber);
            boolean exists = vehicleService.existsByLicensePlate(plateNumber);
            return Result.success("检查车牌号是否存在成功", exists);
        } catch (Exception e) {
            log.error("检查车牌号是否存在失败", e);
            return Result.error("检查车牌号是否存在失败: " + e.getMessage());
        }
    }

    /**
     * 更新车辆状态
     *
     * @param id     车辆ID
     * @param status 状态
     * @return 更新结果
     */
    @Log(title = "更新车辆状态", businessType = 2)
    @PostMapping("/{id}/status")
    public Result<Boolean> updateStatus(@PathVariable("id") Long id, @RequestParam Integer status) {
        try {
            log.info("更新车辆状态请求: id={}, status={}", id, status);
            boolean success = vehicleService.updateStatus(id, status);
            return Result.success("车辆状态更新成功", success);
        } catch (Exception e) {
            log.error("更新车辆状态失败", e);
            return Result.error("更新车辆状态失败: " + e.getMessage());
        }
    }

    /**
     * 更新车辆里程
     *
     * @param id      车辆ID
     * @param mileage 里程
     * @return 更新结果
     */
    @Log(title = "更新车辆状态", businessType = 2)
    @PostMapping("/{id}/mileage")
    public Result<Boolean> updateMileage(@PathVariable("id") Long id, @RequestParam BigDecimal mileage) {
        try {
            log.info("更新车辆里程请求: id={}, mileage={}", id, mileage);
            boolean success = vehicleService.updateMileage(id, mileage);
            return Result.success("车辆里程更新成功", success);
        } catch (Exception e) {
            log.error("更新车辆里程失败", e);
            return Result.error("更新车辆里程失败: " + e.getMessage());
        }
    }
}
